package aladyn.id;

import java.util.HashMap;

// On utilise cette class pour traiter les cycles(cinquième palier)
/**
 * 
 * @author YiHan WANG, Qi XU, Bo CAI
 *
 */
public class Identificater {
	
	protected static HashMap<Object, Integer> serializeTab = 
		new HashMap<Object, Integer>();  
	
	protected static HashMap<Integer, Object> deserializeTab = 
		new HashMap<Integer, Object>(); 

	/**
	 * Le dernier id enregistré pour la table serializeTab
	 */
	protected static int serializeLastRegisteredId = -1;
	
	/**
	 * Le dernier id enregistré pour la table deserializeTab
	 */
	protected static int deserializeLastRegisteredId = -1;
	
	public static Integer serializeGet(Object obj){
		return serializeTab.get(obj);
	}
	
	public static Integer serializeRegister(Object obj){
		Integer id = serializeTab.get(obj);
		if(id == null){
			id = new Integer(++serializeLastRegisteredId);
			serializeTab.put(obj, id);
		}
		return id;
	}
	
	public static Object deserializeGet(int id){
		return deserializeTab.get(id);
	}
	
	public static Object deserializeGet(Integer id){
		return deserializeTab.get(id);
	}
	
	public static boolean deserializeRegister(int id, Object obj){
		return deserializeRegister(id, obj);
	}
	
	public static boolean deserializeRegister(Integer id, Object obj){
		if(deserializeTab.containsKey(id))
			return false;
		deserializeTab.put(id, obj);
		return true;
	}
	
	public static int deserializeGetId(Object obj){
		Object o = null;
		for(Integer key : deserializeTab.keySet()){
			o = deserializeTab.get(key);
			if(o == obj)
				return key.intValue();
		}
		return -1;
	}
	
	public static void print(){
		String str = "serializeTab :\n";
		for(Object key : serializeTab.keySet())
			str += serializeTab.get(key) + "\t" + key + "\n";
		
		str += "deserializeTab :\n";
		for(Integer key : deserializeTab.keySet())
			str += key + "\t" + deserializeTab.get(key) + "\n";
		System.out.println(str);
	}
}
